package com.byd.web.utils;

import com.byd.system.domain.SysUser;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class StaticUtils {

    private static String UPLOAD_PATCH;
    private static String TEMPLATE_NAME;
    private static Configuration CONFIG;
    private final static String FORMAT_DATE = "yyyy.MM.dd";
    private final static String FORMAT_DATE_TITLE = "yyyy年MM月dd日";
    private final static String FORMAT_DATE_TIME = "yyyy/MM/dd HH:mm";
    private final static String FORMAT_DATE_TIME_SECOND = "yyyy/MM/dd HH:mm:ss";
    public final static String DEFAULT_TIME_SECOND = " 23:59:59";
    public final static String SUFFIX_FTL = ".ftl";
    public final static String SUFFIX_HTML = ".html";

    @Value("${web.upload-path}")
    private String uploadPatch;

    @Value("${web.template-name}")
    private String templateName;

    @Autowired
    private Configuration config;

    @PostConstruct
    public void init() {
        UPLOAD_PATCH = uploadPatch;
        TEMPLATE_NAME = templateName;
        CONFIG = config;
    }

    /**
     * 构建静态html
     *
     * @throws Exception
     */
    public static void buildStaticHtml(List<SysUser> userList, String fileName) throws Exception {
        Map<String, Object> map = new HashMap<>(32);
        map.put("templateName", TEMPLATE_NAME);
        map.put("name", fileName);
        map.put("users", userList);
        /// 生成静态html
        writerStaticHtml(map);
    }

    /**
     * 构建文件名称
     *
     * @param fileName  文件名称
     * @param occurTime 发生时间
     * @return
     */
    public static String buildFileName(String fileName, Date occurTime) {
        return fileName + formatLocal(occurTime, "yyyyMMddHHmmss");
    }

    private static String formatLocal(Date date, String format) {
        if (StringUtils.isBlank(format)) {
            format = FORMAT_DATE;
        }
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 页面静态化方法
     *
     * @param map 页面元素
     * @throws Exception
     */
    public static void writerStaticHtml(Map<String, Object> map) throws Exception {
        /// 放入文件后缀名
        map.put("suffix", SUFFIX_HTML);
        writerStaticFile(map);
    }

    /**
     * 页面静态化方法
     *
     * @param map 页面元素
     * @throws Exception
     */
    public static void writerStaticFile(Map<String, Object> map) throws Exception {
        //静态化
        CONFIG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        //获取模板
        String templateName = map.get("templateName") + SUFFIX_FTL;
        Template template = CONFIG.getTemplate(templateName);
        //生成最终页面并写到文件
        Writer out = new OutputStreamWriter(new FileOutputStream(UPLOAD_PATCH + File.separator + map.get("name") + map.get("suffix")));

        try {
            //处理
            template.process(map, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * 读取静态html页面
     *
     * @param fileName 名称
     * @return staticHtml.toString() 静态页面html字符串
     */
    public static String readStaticHtml(String fileName) {
        return readStaticFile(fileName, SUFFIX_HTML);
    }

    /**
     * 读取静态html页面
     *
     * @param fileName 名称
     * @param suffix   后缀名
     * @return staticHtml.toString() 静态页面html字符串
     */
    public static String readStaticFile(String fileName, String suffix) {
        StringBuilder staticHtml = new StringBuilder(2048);

        try {
            FileReader fr = new FileReader(UPLOAD_PATCH + File.separator + fileName + suffix);
            BufferedReader br = new BufferedReader(fr);

            String content = "";

            while ((content = br.readLine()) != null) {
                staticHtml.append(content);
            }
        } catch (Exception e) {
            return "";
        }
        return staticHtml.toString();
    }

    /**
     * 文件使用结束 删除临时文件
     *
     * @param fileName
     */
    public static void delete(String fileName) {
        File file = new File(UPLOAD_PATCH + File.separator + fileName + SUFFIX_HTML);
        file.delete();
    }

}
